package com.synjones.handsetS8.ild.adapter.viewholder;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.synjones.handsetS8.R;;
import com.synjones.handsetS8.Utils.util;
import com.synjones.handsetS8.ild.adapter.OnItemChildViewClickListener;
import com.synjones.handsetS8.ild.base.BaseRecyclerHolder;
import com.synjones.handsetS8.ild.net.model.SensorInfo;
import com.synjones.handsetS8.ild.net.model.WorkerResult;
import com.synjones.handsetS8.ild.pages.WorkerListActivity;
import com.synjones.m1card.M1CardInfo;
import com.synjones.reader.IDCardReaderModule;

import java.text.SimpleDateFormat;

/**
 * @author Chris Chan
 * Create on: 2021/7/15}11:26
 * For:
 * Explain:
 */
public class WorkerRvViewHolder extends BaseRecyclerHolder<WorkerResult> {
    private TextView name;
    private TextView teamName;
    private TextView teamLeader;
    private TextView labor;
    private TextView intoDate;
    private ImageView workerPhoto;
    private TextView tvBind;
    private RelativeLayout rlBind;
    private LinearLayout llContainer;
    private LinearLayout llOp;
    private Button btnChange;
    private Button btnQuit;

    private OnItemChildViewClickListener<WorkerResult> onItemChildViewClickListener;

    //手环
    IDCardReaderModule idCardReaderModule;
    boolean isConnect;
    final int MESSAGE_FIND_CARD = 0x51;
    boolean findingCard = false;

    private PopupWindow popupWindowChange;
    private PopupWindow popupWindowQuit;

    public WorkerRvViewHolder(Context context, View itemView) {
        super(context, itemView);

        name = (TextView) itemView.findViewById(R.id.tv_name);
        teamName = (TextView) itemView.findViewById(R.id.tv_team_name);
        teamLeader = (TextView) itemView.findViewById(R.id.tv_team_leader);
        labor = (TextView) itemView.findViewById(R.id.tv_labor);
        intoDate = (TextView) itemView.findViewById(R.id.tv_date);
        workerPhoto = (ImageView) itemView.findViewById(R.id.iv_worker_photo);
        tvBind = (TextView) itemView.findViewById(R.id.tv_bind);
        rlBind = (RelativeLayout) itemView.findViewById(R.id.rl_bind);
        llOp = (LinearLayout) itemView.findViewById(R.id.ll_op);
        llContainer = (LinearLayout) itemView.findViewById(R.id.ll_item_worker);
        btnChange = (Button) itemView.findViewById(R.id.btn_change);
        btnQuit = (Button) itemView.findViewById(R.id.btn_quit);
        llOp.setVisibility(View.GONE);

        workerPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (llOp.getVisibility() == View.GONE) {
                    llOp.setVisibility(View.VISIBLE);
                } else {
                    llOp.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    public void refreshView(WorkerResult item) {
        name.setText(item.getRealname());
        teamName.setText(item.getTeam_name());
        teamLeader.setVisibility(item.isManager() ? View.VISIBLE : View.GONE);
        labor.setText(item.getLabor_name());
        intoDate.setText("进场日期: " + new SimpleDateFormat("yyyy-MM-dd").format(item.getCreated_at() * 1000));
        String faceImg = item.getFace_img();
        if (null == faceImg || "".equals(faceImg.trim()) || !faceImg.startsWith("http://")) {
            Glide.with(context).load(R.drawable.ild_worker_photo_default_001).into(workerPhoto);
        } else {
            Glide.with(context).load(faceImg).into(workerPhoto);
        }
        Drawable d0 = context.getResources().getDrawable(R.drawable.ild_worker_bracelet_0);
        Drawable d1 = context.getResources().getDrawable(R.drawable.ild_worker_bracelet_1);
        Drawable d2 = context.getResources().getDrawable(R.drawable.ild_worker_bracelet_2);
        /*
        备注: 如果该用户有设备信息属于已发放状态，如果没有属于未发放状态，如果有设备信息，并且owner_type=3显示为自带
         */
        int sensorStatus = 0;//未发放
        SensorInfo sensorInfo = item.getSensorInfo();
        if (null == sensorInfo) {
            sensorStatus = 0;
        } else {
            if (sensorInfo.getOwner_type() == 3) {
                sensorStatus = 2;//自带
            } else {
                sensorStatus = 1;//已发放
            }
        }
        rlBind.setBackground(sensorStatus == 0 ? d0 : (sensorStatus == 1 ? d1 : d2));
        tvBind.setText(sensorStatus == 0 ? "未发放" : (sensorStatus == 1 ? "已发放" : "自带"));

        //点击监听 更换手环
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null!=onItemChildViewClickListener){
                    onItemChildViewClickListener.onChildViewClick(btnChange,itemView,getAdapterPosition(),item);
                }
            }
        });

        //退工
        btnQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null!=onItemChildViewClickListener){
                    onItemChildViewClickListener.onChildViewClick(btnQuit,itemView,getAdapterPosition(),item);
                }
            }
        });

    }


    public void setOnItemChildViewClickListener(OnItemChildViewClickListener<WorkerResult> onItemChildViewClickListener) {
        this.onItemChildViewClickListener = onItemChildViewClickListener;
    }

    /**
     * 读取手环的结果
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (MESSAGE_FIND_CARD == msg.what) {
                M1CardInfo m1CardInfo = (M1CardInfo) msg.obj;
                if (m1CardInfo != null) {
                    String braceletCode = m1CardInfo.getCardNoStr();
                    ((TextView) popupWindowChange.getContentView().findViewById(R.id.tv_bracelet_no)).setText(braceletCode);
                    Toast.makeText(context, "已探测到手环", Toast.LENGTH_SHORT).show();
                    //popupWindowChange.dismiss();
                }
            }
        }
    };

    /**
     * 寻卡
     */
    public void FindCard(final int timeout) {
        findingCard = true;
        new Thread(new Runnable() {

            @Override
            public void run() {
                M1CardInfo m1CardInfo = null;
                long t = System.currentTimeMillis();
                while (findingCard && System.currentTimeMillis() - t < timeout && m1CardInfo == null) {
                    m1CardInfo = idCardReaderModule.findM1Card();
                    if (m1CardInfo != null) {
                        mHandler.obtainMessage(MESSAGE_FIND_CARD, m1CardInfo).sendToTarget();
                        break;
                    }
                    util.sleep(50);
                }
                findingCard = false;
                if (m1CardInfo == null)
                    mHandler.obtainMessage(MESSAGE_FIND_CARD, null).sendToTarget();

            }
        }).start();
    }
}
